import { SupplierPriceService } from './../../../../@core/services/supplierPrice/supplier-price.service';
import { Component, ViewChild } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { DialogService, DValidateRules, FormLayout, TableWidthConfig } from 'ng-devui';
import { QuotationItem, SalesQuotation } from 'src/app/@core/data/sale';
import { PurchasePriceSchedule } from 'src/app/@core/data/supplierPrice';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
import { environment } from 'src/environments/environment';
import * as XLSX from 'xlsx';
@Component({
  selector: 'app-supplier-price-edit',
  templateUrl: './supplier-price-edit.component.html',
  styleUrls: ['./supplier-price-edit.component.scss']
})
export class SupplierPriceEditComponent {
  Math = Math;
  msgs: Array<Object> = [];
  UrlHead: any = environment.modifiedApiUrl
  layoutDirection: FormLayout = FormLayout.Horizontal;
  supplierPrice ={
    purchasePriceScheduleId: null,
    purchasePriceScheduleNum: '',
    scheduleName: '',
    PPSSupplyId: null,
    supplyNum: '',
    supplyName: '',
    supplyShortName: '',
    status: '',
    creator: '',
    createDate: null,
    remark: '',
    file: '',
    purchasePriceScheduleParts: [
      {
        purchasePriceSchedulePartId: 0,
        partId: 0,
        partNum: '',
        partName: '',
        partUOM: '',
        partType: '',
        price: 0,
        note: '',
        PPSPId: 0,
        isValid: false,
        startDate: null,
        endDate: null,
        Date:null
      }
    ]
  }
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '价格',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '有效期',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text',
      },
    ]
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px'
    },
    {
      field: '物料编码',
      width: '200px'
    },
    {
      field: '图片',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '规格型号',
      width: '150px'
    },
    {
      field: '物料描述',
      width: '150px'
    },
    {
      field: '单位',
      width: '150px'
    },
    {
      field: '单价(含税)',
      width: '170px'
    },
    {
      field: '有效期',
      width: '370px'
    },
    {
      field: '备注',
      width: '150px'
    }
  ]
  taxRate: number = 13
  customerContact: any
  loadData: boolean
  dataArray=[]
  supplierPriceRules:{[key:string]:DValidateRules}={
    quotationNum:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*销售报价单单号不能为空' },
        { minlength: 2, message: '*销售报价单单号长度至少为2' },
        { maxlength: 40, message: '*销售报价单单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*销售报价单单号不能包含空格' }
      ]
    },
    customerName:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*客户不能为空' },
      ]
    },
    orderDate:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*单据日期不能为空' },
      ]
    },
    partNum:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*物料不能为空' },
      ]
    },
    plannedShipmentDate:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*计划发货时间不能为空' },
      ]
    },
    deliveryDate:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*计划交货时间不能为空' },
      ]
    },
    priceWithTax:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*物料单价不能为空' },
      ]
    },
    quantity:{
      messageShowType:'text',
      validators:[
        { required: true ,message: '*数量不能为空' },
      ]
    }
  }
  fujianNumber: any=0
  constructor( private SupplierPriceService:SupplierPriceService, private DialogService: DialogService,private Router: Router,private ActivatedRoute:ActivatedRoute) { }
  ngOnInit(): void {
    this.ActivatedRoute.params.subscribe((params: any) => {
      this.SupplierPriceService.getSupplierPriceById(params.id).subscribe((res: any) => {
        this.supplierPrice = res;
        this.fujianNumber = this.supplierPrice.file.split(',').length
        if(this.supplierPrice.file==""){
          this.fujianNumber = 0
        }
        this.supplierPrice.createDate = new Date(this.supplierPrice.createDate)
        this.supplierPrice.purchasePriceScheduleParts.forEach((item:any)=>{
          item.startDate = new Date(item.startDate)
          item.endDate = new Date(item.endDate)
          item.Date = [item.startDate,item.endDate]
        })
      })
    })
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.supplierPrice.creator = JSON.parse(userinfoString).username;
    }
    this.supplierPrice.createDate = new Date()
  }
  selectMaterial(rowItem: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择物料',
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.partId = results.modalContentInstance.selectData.partId;
            rowItem.partNum = results.modalContentInstance.selectData.partNum;
            rowItem.partName = results.modalContentInstance.selectData.partName;
            rowItem.partUOM = results.modalContentInstance.selectData.partUOM;
            rowItem.partType = results.modalContentInstance.selectData.partType;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    })
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  addRow() {
    this.supplierPrice.purchasePriceScheduleParts.push({
      purchasePriceSchedulePartId: 0,
      partId: 0,
      partNum: '',
      partName: '',
      partUOM: '',
      partType: '',
      price: 0,
      isValid: false,
      note: '',
      PPSPId: 0,
      startDate: null,
      endDate: null,
      Date: null
    })
  }//添加行
  deleteRow(index: number) {
    this.supplierPrice.purchasePriceScheduleParts.splice(index, 1);
    if(this.supplierPrice.purchasePriceScheduleParts.length==0){
      this.addRow()
    }
  }
  submit($event: any) {
      this.SupplierPriceService.editSupplierPrice(this.supplierPrice.purchasePriceScheduleId,this.supplierPrice).subscribe((res: any) => {
        this.showToast('success', '成功', '更新成功');
        setTimeout(() => {
          this.Router.navigateByUrl('/pages/basicdata/supplier-price')
        }, 1000);
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
    )
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel(){
    this.Router.navigateByUrl('/pages/basicdata/supplier-price')
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '价格表附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '销售附件',
        urls: this.supplierPrice.file
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.supplierPrice.file = results.modalContentInstance.urls;
            this.fujianNumber = this.supplierPrice.file.split(',').length
            results.modalInstance.hide();
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  validateSalesQuotation(supplierPrice: SalesQuotation): boolean {
    // 验证基本信息
    if (!supplierPrice.quotationDate) {
      this.showToast('error', '错误', '报价日期不能为空');
      return false;
    }
    if (!supplierPrice.quotationNum) {
      this.showToast('error', '错误', '销售报价单单号不能为空');
      return false;
    }
    if (!supplierPrice.customerName) {
      this.showToast('error', '错误', '客户名称不能为空');
      return false;
    }
    // 验证 quotationItems 数组
    for (const [index, item] of supplierPrice.quotationItems.entries()) {
      if (!item.partNum) {
        this.showToast('error', '错误', `第${index + 1}行物料编码不能为空`);
        return false;
      }
      if (item.quantity <= 0) {
        this.showToast('error', '错误', `第${index + 1}行数量必须大于0`);
        return false;
      }
      if (item.priceWithTax <= 0) {
        this.showToast('error', '错误', `第${index + 1}行单价(含税)必须大于0`);
        return false;
      }
    }
   return true;
  }   // 所有验证通过
  timeOnChange($event:any,rowItem:any){
    rowItem.startDate = $event[0];
    rowItem.endDate = $event[1];
  }
  selectSupplier(dialogtype?:string){
    const results = this.DialogService.open({
      title: '选择供应商',
      width: '1200px',
      backdropCloseable: false,
      content: SelectSupplierComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              this.supplierPrice.PPSSupplyId = results.modalContentInstance.selectData.supplyId;
              this.supplierPrice.supplyName = results.modalContentInstance.selectData.supplyChineseName;
              this.supplierPrice.supplyNum = results.modalContentInstance.selectData.supplyNum;
              this.supplierPrice.supplyShortName = results.modalContentInstance.selectData.supplyShortName;
            }
            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
